<template>
  <div class="storeList">

    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list v-model:loading="loading" :finished="finished" :finished-text="finishedText" @load="onLoad">
        <div class="storeList_box">
          <div class="storeList_box_item" v-for="(item, index) in storeList" :key="index" @click="toStoreDetails(item.storeId)">
            <div class="storeList_box_item_img">
              <van-image v-if="item.avatar" :src="item.avatar">
                <template v-slot:loading>
                  <van-loading type="spinner" size="20" />
                </template>
              </van-image>
              <i class="iconfont icon-mendian1 storeList_box_item_img_icon" v-else></i>
            </div>
            <div class="storeList_box_item_right">
              <div class="storeList_box_item_right_title">{{ item.storeName }}</div>
              <div class="storeList_box_item_right_address">{{ item.address ? item.address : '暂无地址信息' }}</div>
              <div class="storeList_box_item_right_subTitle">
                <div class="storeList_box_item_right_subTitle_service">已服务 {{ item.personNum }} 人</div>
                <div class="storeList_box_item_right_subTitle_distance">{{ getDistance([item?.lng, item?.lat]) }}</div>
              </div>
              <div class="storeList_box_item_right_phone">
                <i class="iconfont icon-dianhua storeList_box_item_right_phone_iocn"></i>
                <div class="storeList_box_item_right_phone_text">{{ item.phone ? item.phone : '暂无联系方式' }}</div>
              </div>
            </div>
          </div>
        </div>
      </van-list>
    </van-pull-refresh>

    <!-- 骨架屏 -->
    <storeSkeleton v-if="loading" />
    <van-empty v-if="storeList.length == 0" image-size="5rem" description="暂无数据" />

    <!-- 地图 -->
    <div id="container"></div>
  </div>
</template>

<script setup>
import { getStoreListAPI } from '@/api/store'
import { useRouter } from 'vue-router'
import { ref, watch, computed } from 'vue'
import storeSkeleton from './storeSkeleton.vue';

const router = useRouter()

const finishedText = ref('没有更多了')
const loading = ref(false)      // 是否处于加载状态
const finished = ref(false)     // 是否已加载完毕
const refreshing = ref(false)   // 是否处于下拉刷新状态
const pageNum = ref(1)
const pageSize = ref(10)
const storeList = ref([]) // 门店列表
const localAddress = ref('') // 定位地址

const props = defineProps({
  storeName: {
    type: String,
    default: ''
  },
  provinceId: {
    type: String,
    default: ''
  },
  cityId: {
    type: String,
    default: ''
  },
  areaId: {
    type: String,
    default: ''
  }
})


// 计算两点之间的距离
const getDistance = computed(() => (point2) => {
  if (!localAddress.value) return '暂无距离信息'
  if (!point2[0]) return '暂无距离信息'
  const point1 = localAddress.value
  const radLat1 = (point1[0] * Math.PI) / 180.0
  const radLat2 = (point2[0] * Math.PI) / 180.0
  const a = radLat1 - radLat2
  const b = (point1[1] * Math.PI) / 180.0 - (point2[1] * Math.PI) / 180.0
  let s =
    2 *
    Math.asin(
      Math.sqrt(
        Math.pow(Math.sin(a / 2), 2) +
        Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)
      )
    )
  s = s * 6378.137 // EARTH_RADIUS;
  s = Math.round(s * 10000) / 10000
  return '距离' + s.toFixed(2) + 'km'
})


// 获取存储的位置信息bounds
const getLocalAddress = () => {
  const bounds = localStorage.getItem('bounds')
  localAddress.value = bounds.split(';').map(item => {
    return item.split(',')
  }).reduce((prev, cur) => {
    return [((Number(prev[0]) + Number(cur[0])) / 2).toFixed(5), ((Number(prev[1]) + Number(cur[1])) / 2).toFixed(5)]
  })
}
getLocalAddress()


// 获取门店列表
const onLoad = async () => {
  let params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value
  }
  let data = {
    storeName: props.storeName,
    provinceId: props.provinceId,
    cityId: props.cityId,
    areaId: props.areaId
  }
  await getStoreListAPI(params, data).then(res => {
    console.log('获取门店列表', res)

    storeList.value = storeList.value.concat(res.rows)
    pageNum.value++

    if (res.total <= storeList.value.length) {
      finished.value = true
    } else {
      finished.value = false
    }
    if (res.total == 0) {
      finishedText.value = ''
    }
  }).catch(err => {
    console.log(err)
    finished.value = true
  }).finally(() => {
    loading.value = false
    refreshing.value = false
  })
}

// 下拉刷新
const onRefresh = () => {
  pageNum.value = 1
  storeList.value = []

  finished.value = false
  loading.value = true
  onLoad()
}


// 跳转门店详情
const toStoreDetails = (id) => {
  router.push({
    path: '/storeDetails',
    query: {
      id,
      dynamicKeepAlive: 0
    }
  })
}

// 监听props变化
watch(() => props, (val, oldVal) => {
  onRefresh()
}, { immediate: true, deep: true })

</script>

<style lang="scss" scoped>
// 骨架屏
:deep(.van-skeleton) {
  padding: 0;
}

.storeList {
  &_box {
    // padding: 0 .2667rem .4rem;
    background-color: #fff;
    display: flex;
    flex-direction: column;

    &_item {
      width: 100%;
      display: flex;
      padding-bottom: .2667rem;
      margin-bottom: .6667rem;
      border-bottom: 1px solid #f3f3f3;

      &_img {
        width: 1.6rem;
        height: 1.6rem;
        margin-right: .32rem;
        border-radius: .16rem;
        overflow: hidden;
        background-color: #f8f8f8;
        display: flex;
        justify-content: center;
        align-items: center;

        :deep(.van-image) {
          width: 100%;
          height: 100%;
          object-fit: cover;
          z-index: 1;

          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
        }

        &_icon {
          font-size: 1rem;
          color: rgb(228, 228, 228);
        }
      }

      &_right {
        flex: 1;

        &_title {
          font-size: .4rem;
          font-weight: bold;
          color: #333;
          line-height: 1.5;
        }

        &_address {
          font-size: .32rem;
          color: #999;
          line-height: 1.5;
        }

        &_subTitle {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-top: .2667rem;

          &_service {
            font-size: .32rem;
            color: #999;
          }

          &_distance {
            font-size: .32rem;
            color: #999;
          }
        }

        &_phone {
          display: flex;
          align-items: center;
          margin-top: .2667rem;

          &_iocn {
            font-size: .4rem;
            color: #999;
          }

          &_text {
            margin-left: .16rem;
            font-size: .32rem;
            color: #999;
          }
        }
      }
    }
  }
}
</style>